import 'package:flutter/material.dart';
import 'package:xrenovation/api/project.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/widgets/custom_app_bar.dart';
import 'package:xrenovation/widgets/custom_button.dart';
import 'package:xrenovation/widgets/custom_text_field.dart';
import 'package:xrenovation/widgets/header_box.dart';
import 'package:xrenovation/widgets/shadow_card.dart';

class ProjectsPage extends StatefulWidget {
  const ProjectsPage({super.key});

  @override
  State<ProjectsPage> createState() => _ProjectsPageState();
}

class _ProjectsPageState extends State<ProjectsPage> {
  List<dynamic> projects = [];
  List<dynamic> currencyUnits = [];
  bool _isLoading = true;
  bool _isAddingProject = false;
  bool _isUpdatingProject = false;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);

    return HeaderBox(
      child: Scaffold(
        appBar: CustomAppBar(
          title: localizations.translate('projects_page_title'),
          actionName: localizations.translate('add_project'),
          actionIcon: Icons.add,
          action: _showAddProjectDialog,
        ),
        body: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          behavior: HitTestBehavior.opaque,
          child: _buildBody(localizations, theme),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Widget _buildBody(AppLocalizations localizations, ThemeData theme) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (projects.isEmpty) {
      return Center(
        child: Text(
          localizations.translate('no_projects'),
          style: theme.textTheme.bodyLarge?.copyWith(color: theme.hintColor),
          textAlign: TextAlign.center,
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Column(
        children: [
          for (var project in projects)
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
              child: _buildProjectCard(project, localizations, theme),
            ),
          const SizedBox(height: 40),
        ],
      ),
    );
  }

  Widget _buildBudgetInput(
    TextEditingController controller,
    String selectedCurrency,
    AppLocalizations localizations,
    ThemeData theme,
    ValueChanged<String?> onCurrencyChanged,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          localizations.translate('budget'),
          style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: CustomTextField(
                controller: controller,
                keyboardType: TextInputType.number,
                label: localizations.translate('budget'),
                hiddenLabel: true,
                hintText: localizations.translate('budget_hint'),
                prefixText: _getCurrencySymbol(selectedCurrency),
              ),
            ),
            const SizedBox(width: 10),
            SizedBox(
              width: 188,
              child: DropdownButtonFormField<String>(
                value: selectedCurrency,
                hint: Text(
                  localizations.translate('select_budget'),
                  style: theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.4)),
                ),
                items:
                    currencyUnits.map((unit) {
                      return DropdownMenuItem<String>(
                        value: unit['code'],
                        child: Container(
                          constraints: BoxConstraints(maxWidth: 128),
                          child: Text(unit['name'], maxLines: 1, overflow: TextOverflow.ellipsis),
                        ),
                      );
                    }).toList(),
                onChanged: onCurrencyChanged,
                decoration: InputDecoration(
                  border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(8))),
                  contentPadding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: BorderSide(color: theme.colorScheme.outline.withOpacity(0.5)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: BorderSide(color: theme.colorScheme.primary, width: 1.5),
                  ),
                  errorBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: BorderSide(color: theme.colorScheme.error),
                  ),
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Text(
          localizations.translate('budget_desc'),
          style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
        ),
      ],
    );
  }

  Widget _buildDialogHeader(String title, String subtitle, ThemeData theme, VoidCallback onClose) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(title, style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
              const SizedBox(height: 8),
              Text(subtitle, style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor)),
            ],
          ),
        ),
        IconButton(icon: const Icon(Icons.close), onPressed: onClose),
      ],
    );
  }

  Widget _buildProgressRow({
    required String label,
    required String value,
    required double progress,
    required Color color,
    required String description,
    required ThemeData theme,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [Text(label, style: theme.textTheme.bodyMedium), Text(value, style: theme.textTheme.bodyMedium)],
        ),
        const SizedBox(height: 8),
        SizedBox(
          height: 8,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: progress,
              backgroundColor: theme.colorScheme.primary.withOpacity(0.1),
              valueColor: AlwaysStoppedAnimation<Color>(color),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(description, style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor)),
      ],
    );
  }

  Widget _buildProjectActions(dynamic project, AppLocalizations localizations) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
          icon: const Icon(Icons.edit),
          tooltip: localizations.translate('edit'),
          onPressed: () => _showEditProjectDialog(project, localizations),
        ),
        IconButton(
          icon: const Icon(Icons.delete),
          tooltip: localizations.translate('delete'),
          onPressed: () => _showDeleteDialog(project['id'], localizations),
        ),
      ],
    );
  }

  Widget _buildProjectCard(dynamic project, AppLocalizations localizations, ThemeData theme) {
    final tasks = project['tasks'] as List? ?? [];
    final completedTasks = tasks.where((t) => t['status'] == 1).length;
    final progress = tasks.isEmpty ? 0.0 : completedTasks / tasks.length;

    final totalPaid = tasks.fold<double>(0, (sum, task) => sum + (task['paymentAmount'] ?? 0));
    final budget = (project['budget'] as num?)?.toDouble() ?? 0.0;
    final budgetProgress = budget == 0 ? 0.0 : totalPaid / budget;

    final unitCode = project['unitCode'] as String? ?? 'USD';
    final unit = currencyUnits.firstWhere(
      (u) => u['code'] == unitCode,
      orElse: () => {'symbol': '\$', 'name': 'US Dollar'},
    );

    return ShadowCard(
      padding: const EdgeInsets.fromLTRB(6, 16, 16, 16),
      onTap: () {
        Navigator.pushNamed(context, '/tasks', arguments: {'projectId': project['id']});
      },
      child: Padding(
        padding: const EdgeInsets.all(0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            IconButton(icon: Icon(Icons.description, color: theme.colorScheme.primary), onPressed: null),
            const SizedBox(width: 4),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          project['name'] ?? '',
                          style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
                        ),
                      ),
                      _buildProjectActions(project, localizations),
                    ],
                  ),
                  const SizedBox(height: 20),
                  _buildProgressRow(
                    label: localizations.translate('task_progress'),
                    value: '${(progress * 100).toStringAsFixed(0)}%',
                    progress: progress,
                    color: const Color(0xFF155DFC),
                    description: localizations
                        .translate('tasks_completed')
                        .replaceAll('{completed}', '$completedTasks')
                        .replaceAll('{total}', '${tasks.length}'),
                    theme: theme,
                  ),
                  const SizedBox(height: 20),
                  _buildProgressRow(
                    label: localizations.translate('budget'),
                    value:
                        '${unit['symbol']}${totalPaid.toStringAsFixed(2)} / ${unit['symbol']}${budget.toStringAsFixed(2)}',
                    progress: budgetProgress,
                    color: const Color(0xFF00C951),
                    description: localizations
                        .translate('remaining')
                        .replaceAll('{amount}', '${unit['symbol']}${(budget - totalPaid).toStringAsFixed(2)}'),
                    theme: theme,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _getCurrencySymbol(String currencyCode) {
    final unit = currencyUnits.firstWhere((u) => u['code'] == currencyCode, orElse: () => {'symbol': '\$'});
    return '${unit['symbol']} ';
  }

  Future<void> _handleAddProject(
    GlobalKey<FormState> formKey,
    TextEditingController nameController,
    TextEditingController descriptionController,
    TextEditingController budgetController,
    String selectedCurrency,
    AppLocalizations localizations,
  ) async {
    if (!(formKey.currentState?.validate() ?? false)) return;

    try {
      final res = await ProjectApi.addProject({
        'name': nameController.text,
        'description': descriptionController.text,
        'budget': budgetController.text.isEmpty ? null : double.tryParse(budgetController.text),
        'unitCode': selectedCurrency,
      });

      if (res['code'] == 200) {
        MessageUtil.success(localizations.translate('project_add_success'));
        Navigator.pop(context);
        _loadData();
      } else {
        MessageUtil.error(res['message'] ?? 'Failed to add project');
      }
    } catch (e) {
      MessageUtil.error('Failed to add project');
    }
  }

  Future<void> _handleDeleteProject(String projectId, AppLocalizations localizations) async {
    final closeLoading = MessageUtil.loading(localizations.translate('deleting'));
    try {
      final res = await ProjectApi.deleteProject(projectId);

      if (res['code'] == 200) {
        MessageUtil.success(localizations.translate('delete_success'));
        _loadData();
      } else {
        MessageUtil.error(res['message'] ?? 'Failed to delete project');
      }
    } catch (e) {
      MessageUtil.error('Failed to delete project');
    } finally {
      closeLoading();
    }
  }

  Future<void> _handleUpdateProject(
    String projectId,
    String projectName,
    String? projectDescription,
    TextEditingController budgetController,
    String selectedCurrency,
    AppLocalizations localizations,
  ) async {
    try {
      final res = await ProjectApi.updateProject({
        'id': projectId,
        'name': projectName,
        'description': projectDescription,
        'budget': budgetController.text.isEmpty ? null : double.tryParse(budgetController.text),
        'unitCode': selectedCurrency,
      });

      if (res['code'] == 200) {
        MessageUtil.success(localizations.translate('project_update_success'));
        Navigator.pop(context);
        _loadData();
      } else {
        MessageUtil.error(res['message'] ?? 'Failed to update project');
      }
    } catch (e) {
      MessageUtil.error('Failed to update project');
    }
  }

  Future<void> _loadData() async {
    setState(() => _isLoading = true);
    try {
      final projectsRes = await ProjectApi.getProjectList();
      final unitsRes = await ProjectApi.getCurrencyUnits();

      if (mounted) {
        setState(() {
          projects = projectsRes['data'] ?? [];
          currencyUnits = unitsRes['data'] ?? [];
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        MessageUtil.error('Failed to load projects');
      }
    }
  }

  void _showAddProjectDialog() {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final formKey = GlobalKey<FormState>();
    final nameController = TextEditingController();
    final descriptionController = TextEditingController();
    final budgetController = TextEditingController();
    String selectedCurrency = 'USD';

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              behavior: HitTestBehavior.opaque,
              child: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: Container(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildDialogHeader(
                        localizations.translate('create_project_title'),
                        localizations.translate('create_project_desc'),
                        theme,
                        () => Navigator.pop(context),
                      ),
                      const SizedBox(height: 24),
                      Expanded(
                        child: SingleChildScrollView(
                          child: Form(
                            key: formKey,
                            child: Column(
                              children: [
                                CustomTextField(
                                  controller: nameController,
                                  label: localizations.translate('project_name'),
                                  labelMark: true,
                                  hintText: localizations.translate('project_name_hint'),
                                  validator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return localizations.translate('project_name_required');
                                    }
                                    return null;
                                  },
                                ),
                                const SizedBox(height: 16),
                                CustomTextField(
                                  controller: descriptionController,
                                  label: localizations.translate('project_description'),
                                  hintText: localizations.translate('project_description_hint'),
                                  maxLines: 3,
                                ),
                                const SizedBox(height: 16),
                                _buildBudgetInput(
                                  budgetController,
                                  selectedCurrency,
                                  localizations,
                                  theme,
                                  (value) => setState(() => selectedCurrency = value!),
                                ),
                                const SizedBox(height: 40),
                                CustomButton(
                                  title: localizations.translate('create_project'),
                                  isLoading: _isAddingProject,
                                  onTap: () async {
                                    setState(() => _isAddingProject = true);
                                    await _handleAddProject(
                                      formKey,
                                      nameController,
                                      descriptionController,
                                      budgetController,
                                      selectedCurrency,
                                      localizations,
                                    );
                                    if (mounted) setState(() => _isAddingProject = false);
                                  },
                                ),
                                const SizedBox(height: 10),
                                CustomButton(
                                  title: localizations.translate('cancel'),
                                  isOutlined: true,
                                  onTap: () => Navigator.pop(context),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  void _showDeleteDialog(String projectId, AppLocalizations localizations) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text(localizations.translate('delete_confirm_title')),
            content: Text(localizations.translate('delete_confirm_content')),
            actions: [
              TextButton(onPressed: () => Navigator.pop(context), child: Text(localizations.translate('cancel'))),
              TextButton(
                onPressed: () async {
                  Navigator.pop(context);
                  await _handleDeleteProject(projectId, localizations);
                },
                child: Text(
                  localizations.translate('delete'),
                  style: TextStyle(color: Theme.of(context).colorScheme.error),
                ),
              ),
            ],
          ),
    );
  }

  void _showEditProjectDialog(dynamic project, AppLocalizations localizations) {
    final theme = Theme.of(context);
    final formKey = GlobalKey<FormState>();
    final budgetController = TextEditingController(text: project['budget']?.toString() ?? '');
    String selectedCurrency = project['unitCode'] ?? 'USD';

    final tasks = project['tasks'] as List? ?? [];
    final totalPaid = tasks.fold<double>(0, (sum, task) => sum + (task['paymentAmount'] ?? 0));

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              behavior: HitTestBehavior.opaque,
              child: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: Container(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildDialogHeader(
                        localizations.translate('edit_project_title'),
                        localizations.translate('edit_project_desc'),
                        theme,
                        () => Navigator.pop(context),
                      ),
                      const SizedBox(height: 16),
                      Text(project['name'] ?? '', style: theme.textTheme.titleMedium),
                      const SizedBox(height: 16),
                      Text(
                        localizations.translate('current_spent'),
                        style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '${_getCurrencySymbol(selectedCurrency)}${totalPaid.toStringAsFixed(2)}',
                        style: theme.textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(height: 16),
                      Expanded(
                        child: SingleChildScrollView(
                          child: Form(
                            key: formKey,
                            child: Column(
                              children: [
                                _buildBudgetInput(
                                  budgetController,
                                  selectedCurrency,
                                  localizations,
                                  theme,
                                  (value) => setState(() => selectedCurrency = value!),
                                ),
                                const SizedBox(height: 40),
                                CustomButton(
                                  title: localizations.translate('save_changes'),
                                  isLoading: _isUpdatingProject,
                                  onTap: () async {
                                    setState(() => _isUpdatingProject = true);
                                    await _handleUpdateProject(
                                      project['id'],
                                      project['name'],
                                      project['description'],
                                      budgetController,
                                      selectedCurrency,
                                      localizations,
                                    );
                                    if (mounted) setState(() => _isUpdatingProject = false);
                                  },
                                ),
                                const SizedBox(height: 10),
                                CustomButton(
                                  title: localizations.translate('cancel'),
                                  isOutlined: true,
                                  onTap: () => Navigator.pop(context),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
